package com.hmdp.controller;


import com.hmdp.dto.Result;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.service.impl.SeckillVoucherServiceImpl;
import com.hmdp.service.impl.VoucherOrderServiceImpl;
import com.hmdp.utils.IncreaseIdUtils;
import com.hmdp.utils.LockUtils;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static com.hmdp.constants.RedisConstants.*;

@RestController
@RequestMapping("/voucher-order")
@Slf4j
public class VoucherOrderController {

    @Resource
    private IncreaseIdUtils increaseIdUtils;
    @Resource
    private SeckillVoucherServiceImpl seckillVoucherService;
    @Resource
    private VoucherOrderServiceImpl voucherOrderService;
    @Resource
    private LockUtils lockUtils;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private static final DefaultRedisScript<Long> CHECK_SCRIPT;
    static {
        CHECK_SCRIPT = new DefaultRedisScript<>();
        CHECK_SCRIPT.setLocation(new ClassPathResource("checkIsVoucherKill.lua"));
        CHECK_SCRIPT.setResultType(Long.class);
    }

    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;
    static {
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        UNLOCK_SCRIPT.setResultType(Long.class);
    }

    private final BlockingQueue<VoucherOrder> blockingQueue = new ArrayBlockingQueue<>(1024 * 1204);
    private static final ExecutorService EXECUTOR_SERVICE = Executors.newSingleThreadExecutor();

    @PostConstruct
    private void init() {
         EXECUTOR_SERVICE.submit(new VoucherOrderHandler());
    }

    private class VoucherOrderHandler implements Runnable {
        @Override
        public void run() {
            try {
                while (true) {
                    // 获取订单信息
                    VoucherOrder voucherOrder = blockingQueue.take();
                    // 扣减库存
                    boolean success = seckillVoucherService.update()
                            .setSql("stock = stock - 1")
                            .eq("voucher_id", voucherOrder.getVoucherId())
                            .update();

                    // 插入订单
                    voucherOrderService.save(voucherOrder);
                }
            } catch (Exception e) {
                log.error("阻塞队列插入订单错误", e);
            }
        }
    }

    @PostMapping("seckill/{id}")
    public Result seckillVoucher(@PathVariable("id") Long voucherId) {
        // TODO 是否在秒杀时间范围内

        // lua脚本检查是否有购买资格（满足一人一单和库存大于0）
        ArrayList<String> keys = new ArrayList<>();
        keys.add(CACHE_VOUCHER_KILL_STOCK + voucherId);
        keys.add(CACHE_VOUCHER_KILL_USERS + voucherId);
        Long result = stringRedisTemplate.execute(
                CHECK_SCRIPT,
                keys,
                UserHolder.getUser().getId().toString()
        );

        if (result == null) {
            return Result.fail("服务器错误");
        }

        // 1.无库存
        if (result == 1L) {
            return Result.fail("库存为0，抢购失败！");
        }
        // 2.一人一单
        if (result == 2L) {
            return Result.fail("一人只能抢一单！");
        }

        // log.info("id为：{}的用户抢券成功", UserHolder.getUser().getId());

        // 阻塞队列完成数据库修改
        VoucherOrder voucherOrder = VoucherOrder.builder()
                .id(increaseIdUtils.getId())
                .userId(UserHolder.getUser().getId())
                .voucherId(voucherId)
                .build();
        blockingQueue.add(voucherOrder);



        return Result.ok();
    }

    // @PostMapping("seckill/{id}")
    public Result seckillVoucherOrderVersion(@PathVariable("id") Long voucherId) {
        // 1.查询数据库
        SeckillVoucher voucher = seckillVoucherService.getById(voucherId);
        if (voucher == null) {
            return Result.fail("非法优惠券id");
        }

        // 2.判断是否在秒杀时间范围内
        LocalDateTime now = LocalDateTime.now();
        if (voucher.getBeginTime().isAfter(now) || voucher.getEndTime().isBefore(now)) {
            return Result.fail("秒杀券还未开抢或已结束");
        }

        // 3.检查库存
        if (voucher.getStock() < 1) {
            return Result.fail("库存不足");
        }

        // 4.实现一人一单 redis分布式锁
        Long userId = UserHolder.getUser().getId();
        String inLock = UUID.randomUUID() + Thread.currentThread().getName();
        boolean lock = lockUtils.tryLock("oneUserByOneOrder", userId, inLock);
        if (!lock) {
            return Result.fail("一人只能买一单");
        }

        // 5.执锁操作，释放锁资源
        Result result = createOrder(userId, voucherId);

        // 5.1.存在并发安全问题
        // 检查是否是自己的锁
//        String currentLock = stringRedisTemplate.opsForValue().get(LOCK_KEY + "oneUserByOneOrder" + ":" + userId);
//        if (inLock.equals(currentLock)) {
//            lockUtils.removeLock("oneUserByOneOrder", userId);
//        }

        // 5.2.采用lua脚本 保证检查和删除操作的原子性
        stringRedisTemplate.execute(
                UNLOCK_SCRIPT,
                Collections.singletonList(LOCK_KEY + "oneUserByOneOrder:" + userId),
                inLock
        );

        return result;
    }

    public Result createOrder(Long userId, Long voucherId) {
        // 查询订单是否存在
        Integer count = voucherOrderService.query()
                .eq("user_id", userId)
                .eq("voucher_id", voucherId)
                .count();

        // 订单已存在
        if (count > 0) {
            return Result.fail("一人只能买一单");
        }

        // 扣减库存 乐观锁
        boolean success = seckillVoucherService.update()
                .setSql("stock = stock - 1")
                .eq("voucher_id", voucherId)
                .gt("stock", 0)
                .update();

        // 扣减不成功
        if (!success) {
            return Result.fail("扣减失败");
        }

        // 成功，创建订单
        long id = increaseIdUtils.getId();
        VoucherOrder voucherOrder = VoucherOrder.builder()
                .id(id)
                .userId(userId)
                .voucherId(voucherId)
                .build();
        voucherOrderService.save(voucherOrder);
        return Result.ok();
    }
}
